import React from 'react';
import { withRouter } from 'react-router-dom';
import { Modal } from 'weaver-mobile';
import IScroll from 'iscroll';
import { getRouteParams, getIScrollClick, changeTitle } from '../../util';
import NavbarExtend from './NavbarExtend';
import * as API_NAVBAR from '../../apis/navbar';

@withRouter
class Navbar extends React.Component {
  constructor(props) {
    super(props);
    this.getNavbarItems = this.getNavbarItems.bind(this);
    this.getSelectedMenu = this.getSelectedMenu.bind(this);
    this.onClick = this.onClick.bind(this);
    this.onExtend = this.onExtend.bind(this);
    this.onClose = this.onClose.bind(this);

    const menus = localStorage.getItem('portal-navbar-menus');
    this.state = {
      loading: false,
      menus: menus ? JSON.parse(menus) : [],
      selected: 0,
      visible: false
    };
  }

  componentWillMount() {
    const params = getRouteParams(this.props);
    const { hpid: selected } = params;

    API_NAVBAR.getNavbarMenus().then(result => {
      const { menus = [] } = result;
      this.setState({ menus, selected });
      this.getSelectedMenu(menus, selected);
      localStorage.setItem('portal-navbar-menus', JSON.stringify(menus));
    });
  }

  componentWillReceiveProps(nextProps) {
    const params = getRouteParams(nextProps);
    const { hpid: selected } = params;
    this.setState({ selected });
  }

  componentDidUpdate() {
    const height = this.refs['navbar'].offsetHeight;
    if (this.props.navbarHeight != height) {
      this.props.setNavbarHeight(height);
    }

    const ulWidth = this.refs['scroller-ul'].scrollWidth;
    this.refs['scroller'].style.width = ulWidth + 'px';

    if (this.iscroll) {
      this.iscroll.destroy();
      this.iscroll = null;
    }
    this.iscroll = new IScroll(this.refs['wrapper'], {
      click: getIScrollClick(),
      scrollX: true,
      scrollY: false,
      mouseWheel: true,
      bounce: true
    });

    // 将当前选中的菜单滚动到屏幕中央
    const selectedNode = this.refs[`menu-${this.state.selected}`];
    if (selectedNode) {
      const iw = window.innerWidth; // 屏幕宽度
      const bw = iw * 0.85; // 滑动区域宽度
      const ow = selectedNode.offsetWidth; // 当前选中菜单宽度
      const now = selectedNode.nextSibling ? selectedNode.nextSibling.offsetWidth : 0; // 当前选中菜单下一个菜单宽度
      const ol = selectedNode.offsetLeft; // 当前选中菜单左侧距离左侧的距离
      const pfl = ol + ow; // 当前选中菜单右侧距离左侧的距离

      if (pfl > bw) {
        this.iscroll.scrollTo(-Math.round(pfl - bw) - now, 0);
      }
    }
  }

  render() {
    const { menus, selected, visible } = this.state;

    return (
      <div ref="navbar" className="navbar">
        <div className="navbar-content">
          <div ref="wrapper" className="menu-list">
            <div ref="scroller">
              <ul ref="scroller-ul" className="navbar-ul">
                {this.getNavbarItems(menus, selected)}
              </ul>
            </div>
          </div>
          <div className="menu-extend" onClick={this.onExtend} />
        </div>
        <Modal visible={visible} onClose={this.onClose} popup={true} animationType="slide-down">
          <NavbarExtend data={menus} selected={selected} onClick={this.onClick} onClose={this.onClose} />
        </Modal>
      </div>
    );
  }

  getNavbarItems(menus, selected) {
    // 获取选中菜单的同级菜单
    let _menus = this.getSameLevelMenus(menus, selected);
    if (_menus && _menus.length == 0) {
      _menus = menus;
    }

    return _menus.map(item => {
      const { menuid, menuname } = item;
      return (
        <li key={menuid} ref={`menu-${menuid}`} className={menuid == selected ? 'active' : ''} onClick={() => this.onClick(item)}>
          {menuname}
        </li>
      );
    });
  }

  getSameLevelMenus(menus, selected) {
    let _menus = [];
    for (let i = 0, len = menus.length; i < len; i++) {
      const item = menus[i];
      if (item.menuid == selected) {
        _menus = menus;
        break;
      } else if (item.child && item.child.length) {
        _menus = this.getSameLevelMenus(item.child, selected);
        break;
      }
    }
    return _menus;
  }

  getSelectedMenu(menus, selected) {
    for (let i = 0, len = menus.length; i < len; i++) {
      const item = menus[i];
      if (item.menuid == selected) {
        changeTitle(item.infoname);
        break;
      } else if (item.child && item.child.length) {
        this.getSelectedMenu(item.child, selected);
      }
    }
  }

  onClick(item) {
    const { id: hpid, subcompanyid: subCompanyId, infoname } = item;
    this.props.history.push(`/portal/${hpid}/${subCompanyId}`);
    this.setState({ selected: hpid, visible: false });
    changeTitle(infoname);
  }

  onExtend() {
    this.setState({ visible: true });
  }

  onClose() {
    this.setState({ visible: false });
  }
}

export default Navbar;
